#include "esp_log.h"
#include "w2p_ble_hid.h"
#define REPORT_PROTOCOL_MOUSE_REPORT_SIZE      (4)
#define REPORT_BUFFER_SIZE                     REPORT_PROTOCOL_MOUSE_REPORT_SIZE
#define MAX_REPORT_BUFFER_SIZE (2 + 5 * 5)
#define CONTACT_COUNT_MAXIMUM 10
// #define REPORTID_TOUCH        0x04



static const char *TAG = "BLE_HID";
static bool  proc_busy=false;
static bool _use_multiTouch=false;
typedef struct {
    esp_hidd_app_param_t app_param;
    esp_hidd_qos_param_t both_qos;
    uint8_t protocol_mode;
    SemaphoreHandle_t mouse_mutex;
    TaskHandle_t mouse_task_hdl;
    uint8_t buffer[MAX_REPORT_BUFFER_SIZE];
    int8_t x_dir;
    uint8_t _report_id;
    uint8_t _report_size;
} local_param_t;

static local_param_t s_local_param = {0};


// HID report descriptor for a generic mouse. The contents of the report are:
// 3 buttons, moving information for X and Y cursors, information for a wheel.
uint8_t hid_mouse_descriptor[] = {
    0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
    0x09, 0x02,                    // USAGE (Mouse)
    0xa1, 0x01,                    // COLLECTION (Application)

    0x09, 0x01,                    //   USAGE (Pointer)
    0xa1, 0x00,                    //   COLLECTION (Physical)

    0x05, 0x09,                    //     USAGE_PAGE (Button)
    0x19, 0x01,                    //     USAGE_MINIMUM (Button 1)
    0x29, 0x03,                    //     USAGE_MAXIMUM (Button 3)
    0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
    0x95, 0x03,                    //     REPORT_COUNT (3)
    0x75, 0x01,                    //     REPORT_SIZE (1)
    0x81, 0x02,                    //     INPUT (Data,Var,Abs)
    0x95, 0x01,                    //     REPORT_COUNT (1)
    0x75, 0x05,                    //     REPORT_SIZE (5)
    0x81, 0x03,                    //     INPUT (Cnst,Var,Abs)

    0x05, 0x01,                    //     USAGE_PAGE (Generic Desktop)
    0x09, 0x30,                    //     USAGE (X)
    0x09, 0x31,                    //     USAGE (Y)
    0x09, 0x38,                    //     USAGE (Wheel)
    0x15, 0x81,                    //     LOGICAL_MINIMUM (-127)
    0x25, 0x7f,                    //     LOGICAL_MAXIMUM (127)
    0x75, 0x08,                    //     REPORT_SIZE (8)
    0x95, 0x03,                    //     REPORT_COUNT (3)
    0x81, 0x06,                    //     INPUT (Data,Var,Rel)

    0xc0,                          //   END_COLLECTION
    0xc0                           // END_COLLECTION
};


// 多点触控 HID 报告描述符
const uint8_t hid_mt_mouse_descriptor[] = {
    0x05, 0x0D,        // USAGE_PAGE (Digitizers)
    0x09, 0x04,        // USAGE (Touch Screen)
    0xA1, 0x01,        // COLLECTION (Application)
    0x85, 0x01,        //   REPORT_ID (1)
    0x09, 0x55,        //   USAGE (Contact Count Maximum)
    0x15, 0x00,        //   LOGICAL_MINIMUM (0)
    0x25, 0x05,        //   LOGICAL_MAXIMUM (5)
    0x75, 0x08,        //   REPORT_SIZE (8)
    0x95, 0x01,        //   REPORT_COUNT (1)
    0xB1, 0x02,        //   FEATURE (Data,Var,Abs)
    0x09, 0x54,        //   USAGE (Contact Count)
    0x81, 0x02,        //   INPUT (Data,Var,Abs)
    0x09, 0x22,        //   USAGE (Finger)
    0xA1, 0x02,        //   COLLECTION (Logical)
    0x09, 0x42,        //     USAGE (Tip Switch)
    0x15, 0x00,        //     LOGICAL_MINIMUM (0)
    0x25, 0x01,        //     LOGICAL_MAXIMUM (1)
    0x75, 0x01,        //     REPORT_SIZE (1)
    0x95, 0x01,        //     REPORT_COUNT (1)
    0x81, 0x02,        //     INPUT (Data,Var,Abs)
    0x09, 0x32,        //     USAGE (In Range)
    0x81, 0x02,        //     INPUT (Data,Var,Abs)
    0x75, 0x06,        //     REPORT_SIZE (6)
    0x95, 0x01,        //     REPORT_COUNT (1)
    0x81, 0x03,        //     INPUT (Cnst,Var,Abs)
    0x09, 0x51,        //     USAGE (Contact ID)
    0x15, 0x00,        //     LOGICAL_MINIMUM (0)
    0x25, 0x04,        //     LOGICAL_MAXIMUM (4)
    0x75, 0x08,        //     REPORT_SIZE (8)
    0x95, 0x01,        //     REPORT_COUNT (1)
    0x81, 0x02,        //     INPUT (Data,Var,Abs)
    0x05, 0x01,        //     USAGE_PAGE (Generic Desktop)
    0x09, 0x30,        //     USAGE (X)
    0x09, 0x31,        //     USAGE (Y)
    0x15, 0x00,        //     LOGICAL_MINIMUM (0)
    0x26, 0xFF, 0x03,  //     LOGICAL_MAXIMUM (1023)
    0x75, 0x10,        //     REPORT_SIZE (16)
    0x95, 0x02,        //     REPORT_COUNT (2)
    0x81, 0x02,        //     INPUT (Data,Var,Abs)
    0xC0,              //   END_COLLECTION
    0xC0               // END_COLLECTION
};
// 触摸点结构体
typedef struct {
    uint8_t tip_switch;
    uint8_t contact_id;
    uint16_t x;
    uint16_t y;
} touch_point_t;



#define REPORTID_TOUCH        0x01


#define LSB(v) ((v >> 8) & 0xff)
#define MSB(v) (v & 0xff)

// static const uint8_t _hidReportDescriptor[] = {
//   0x05, 0x0D,                    // USAGE_PAGE(Digitizers)
//   0x09, 0x04,                    // USAGE     (Touch Screen)
//   0xA1, 0x01,                    // COLLECTION(Application)
//   0x85, REPORTID_TOUCH,          //   REPORT_ID (Touch)

//   // define the maximum amount of fingers that the device supports
//   0x09, 0x55,                    //   USAGE (Contact Count Maximum)
//   0x25, 0x05,   //   LOGICAL_MAXIMUM (CONTACT_COUNT_MAXIMUM)
//   0xB1, 0x02,                    //   FEATURE (Data,Var,Abs)

//   // define the actual amount of fingers that are concurrently touching the screen
//   0x09, 0x54,                    //   USAGE (Contact count)
//   0x95, 0x01,                    //   REPORT_COUNT(1)
//   0x75, 0x08,                    //   REPORT_SIZE (8)
//   0x81, 0x02,                    //   INPUT (Data,Var,Abs)

//   // declare a finger collection
//   0x09, 0x22,                    //   USAGE (Finger)
//   0xA1, 0x02,                    //   COLLECTION (Logical)

//   // declare an identifier for the finger
//   0x09, 0x51,                    //     USAGE (Contact Identifier)
//   0x75, 0x08,                    //     REPORT_SIZE (8)
//   0x95, 0x01,                    //     REPORT_COUNT (1)
//   0x81, 0x02,                    //     INPUT (Data,Var,Abs)

//   // declare Tip Switch and In Range
//   0x09, 0x42,                    //     USAGE (Tip Switch)
//   0x09, 0x32,                    //     USAGE (In Range)
//   0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
//   0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
//   0x75, 0x01,                    //     REPORT_SIZE (1)
//   0x95, 0x02,                    //     REPORT_COUNT(2)
//   0x81, 0x02,                    //     INPUT (Data,Var,Abs)

//   // declare the remaining 6 bits of the first data byte as constant -> the driver will ignore them
//   0x95, 0x06,                    //     REPORT_COUNT (6)
//   0x81, 0x03,                    //     INPUT (Cnst,Ary,Abs)

//   // define absolute X and Y coordinates of 16 bit each (percent values multiplied with 100)
//   0x05, 0x01,                    //     USAGE_PAGE (Generic Desktop)
//   0x09, 0x30,                    //     Usage (X)
//   0x09, 0x31,                    //     Usage (Y)
//   0x16, 0x00, 0x00,              //     Logical Minimum (0)
//   0x26, 0x10, 0x27,              //     Logical Maximum (10000)
//   0x36, 0x00, 0x00,              //     Physical Minimum (0)
//   0x46, 0x10, 0x27,              //     Physical Maximum (10000)
//   0x66, 0x00, 0x00,              //     UNIT (None)
//   0x75, 0x10,                    //     Report Size (16),
//   0x95, 0x02,                    //     Report Count (2),
//   0x81, 0x02,                    //     Input (Data,Var,Abs)
//   0xC0,                          //   END_COLLECTION
//   0xC0                           // END_COLLECTION

//   // with this declaration a data packet must be sent as:
//   // byte 1   -> "contact count"        (always == 1)
//   // byte 2   -> "contact identifier"   (any value)
//   // byte 3   -> "Tip Switch" state     (bit 0 = Tip Switch up/down, bit 1 = In Range)
//   // byte 4,5 -> absolute X coordinate  (0...10000)
//   // byte 6,7 -> absolute Y coordinate  (0...10000)
// };


static const uint8_t _hidReportDescriptor[] = {
  0x05, 0x0D,                    // USAGE_PAGE(Digitizers)
  0x09, 0x04,                    // USAGE     (Touch Screen)
  0xA1, 0x01,                    // COLLECTION(Application)
  0x85, REPORTID_TOUCH,          //   REPORT_ID (Touch)

  // define the maximum amount of fingers that the device supports
  0x09, 0x55,                    //   USAGE (Contact Count Maximum)
  0x25, 0x05,   //   LOGICAL_MAXIMUM (CONTACT_COUNT_MAXIMUM)
  0xB1, 0x02,                    //   FEATURE (Data,Var,Abs)

  // define the actual amount of fingers that are concurrently touching the screen
  0x09, 0x54,                    //   USAGE (Contact count)
  0x95, 0x01,                    //   REPORT_COUNT(1)
  0x75, 0x08,                    //   REPORT_SIZE (8)
  0x81, 0x02,                    //   INPUT (Data,Var,Abs)

  // declare a finger collection
  0x09, 0x22,                    //   USAGE (Finger)
  0xA1, 0x02,                    //   COLLECTION (Logical)

  // declare an identifier for the finger
  0x09, 0x51,                    //     USAGE (Contact Identifier)
  0x75, 0x08,                    //     REPORT_SIZE (8)
  0x95, 0x01,                    //     REPORT_COUNT (1)
  0x81, 0x02,                    //     INPUT (Data,Var,Abs)

  // declare Tip Switch and In Range
  0x09, 0x42,                    //     USAGE (Tip Switch)
  0x09, 0x32,                    //     USAGE (In Range)
  0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
  0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
  0x75, 0x01,                    //     REPORT_SIZE (1)
  0x95, 0x02,                    //     REPORT_COUNT(2)
  0x81, 0x02,                    //     INPUT (Data,Var,Abs)

  // declare the remaining 6 bits of the first data byte as constant -> the driver will ignore them
  0x95, 0x06,                    //     REPORT_COUNT (6)
  0x81, 0x03,                    //     INPUT (Cnst,Ary,Abs)

  // define absolute X and Y coordinates of 16 bit each (percent values multiplied with 100)
  0x05, 0x01,                    //     USAGE_PAGE (Generic Desktop)
  0x09, 0x30,                    //     Usage (X)
  0x09, 0x31,                    //     Usage (Y)
  0x16, 0x00, 0x00,              //     Logical Minimum (0)
  0x26, 0x10, 0x27,              //     Logical Maximum (10000)
  0x36, 0x00, 0x00,              //     Physical Minimum (0)
  0x46, 0x10, 0x27,              //     Physical Maximum (10000)
  0x66, 0x00, 0x00,              //     UNIT (None)
  0x75, 0x10,                    //     Report Size (16),
  0x95, 0x02,                    //     Report Count (2),
  0x81, 0x02,                    //     Input (Data,Var,Abs)
  0xC0,                          //   END_COLLECTION
  0xC0                           // END_COLLECTION

  // with this declaration a data packet must be sent as:
  // byte 1   -> "contact count"        (always == 1)
  // byte 2   -> "contact identifier"   (any value)
  // byte 3   -> "Tip Switch" state     (bit 0 = Tip Switch up/down, bit 1 = In Range)
  // byte 4,5 -> absolute X coordinate  (0...10000)
  // byte 6,7 -> absolute Y coordinate  (0...10000)
};


typedef struct Finger {
  int contact;
  int16_t x;
  int16_t y;
} Finger;

Finger fingers[CONTACT_COUNT_MAXIMUM];

static char *bda2str(esp_bd_addr_t bda, char *str, size_t size)
{
    if (bda == NULL || str == NULL || size < 18) {
        return NULL;
    }

    uint8_t *p = bda;
    sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
            p[0], p[1], p[2], p[3], p[4], p[5]);
    return str;
}

const int hid_mouse_descriptor_len = sizeof(hid_mouse_descriptor);
const int hid_mt_mouse_descriptor_len = sizeof(hid_mt_mouse_descriptor);
const int hid_android_descriptor_len = sizeof(_hidReportDescriptor);
/**
 * @brief Integrity check of the report ID and report type for GET_REPORT request from HID host.
 *        Boot Protocol Mode requires report ID. For Report Protocol Mode, when the report descriptor
 *        does not declare report ID Global ITEMS, the report ID does not exist in the GET_REPORT request,
 *        and a value of 0 for report_id will occur in ESP_HIDD_GET_REPORT_EVT callback parameter.
 */
bool check_report_id_type(uint8_t report_id, uint8_t report_type)
{
    bool ret = false;
    xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
    do {
        if (report_type != ESP_HIDD_REPORT_TYPE_INPUT) {
            break;
        }
        if (s_local_param.protocol_mode == ESP_HIDD_BOOT_MODE) {
            if (report_id == ESP_HIDD_BOOT_REPORT_ID_MOUSE) {
                ret = true;
                break;
            }
        } else {
            if (report_id == 0) {
                ret = true;
                break;
            }
        }
    } while (0);

    if (!ret) {
        if (s_local_param.protocol_mode == ESP_HIDD_BOOT_MODE) {
            esp_bt_hid_device_report_error(ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID);
        } else {
            esp_bt_hid_device_report_error(ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID);
        }
    }
    xSemaphoreGive(s_local_param.mouse_mutex);
    return ret;
}

// send the buttons, change in x, and change in y
void send_mouse_report(uint8_t buttons, char dx, char dy, char wheel)
{
    uint8_t report_id;
    uint16_t report_size;
    xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
    if (s_local_param.protocol_mode == ESP_HIDD_REPORT_MODE) {
        report_id = 0;
        report_size = REPORT_PROTOCOL_MOUSE_REPORT_SIZE;
        s_local_param._report_id=report_id;
        s_local_param._report_size=report_size;
        s_local_param.buffer[0] = buttons;
        s_local_param.buffer[1] = dx;
        s_local_param.buffer[2] = dy;
        s_local_param.buffer[3] = wheel;
    } else {
        // Boot Mode
        report_id = ESP_HIDD_BOOT_REPORT_ID_MOUSE;
        report_size = ESP_HIDD_BOOT_REPORT_SIZE_MOUSE - 1;
        s_local_param._report_id=report_id;
        s_local_param._report_size=report_size;
        s_local_param.buffer[0] = buttons;
        s_local_param.buffer[1] = dx;
        s_local_param.buffer[2] = dy;
    }
    esp_bt_hid_device_send_report(ESP_HIDD_REPORT_TYPE_INTRDATA, 
    s_local_param._report_id, 
    s_local_param._report_size, s_local_param.buffer);
    xSemaphoreGive(s_local_param.mouse_mutex);
}

// 发送多点触控报告
void send_mt_report(uint8_t contact_count, touch_point_t *points) {
    uint8_t report_size = 2 + contact_count * 5;
    // uint8_t report[report_size];
    uint8_t report_id=0x01;
    s_local_param._report_id=report_id;
    s_local_param._report_size=report_size;    
    s_local_param.buffer[0] = report_id;  // 报告 ID
    s_local_param.buffer[1] = contact_count;  // 触摸点数量
    xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
    for (int i = 0; i < contact_count; i++) {
        s_local_param.buffer[2 + i * 5] = points[i].tip_switch;  // 触摸开关
        s_local_param.buffer[3 + i * 5] = points[i].contact_id;  // 触摸 ID
        s_local_param.buffer[4 + i * 5] = points[i].x & 0xFF;    // X 坐标低字节
        s_local_param.buffer[5 + i * 5] = (points[i].x >> 8) & 0xFF;  // X 坐标高字节
        s_local_param.buffer[6 + i * 5] = points[i].y & 0xFF;    // Y 坐标低字节
        s_local_param.buffer[7 + i * 5] = (points[i].y >> 8) & 0xFF;  // Y 坐标高字节
        ESP_LOGI(TAG,"mv to (%d,%d), is pressed:%d",points[i].x,points[i].y,points[i].tip_switch);
    }

    // esp_err_t ret = esp_bt_hid_device_send_report(ESP_BT_HID_REPORT_TYPE_INPUT, report_id, report_size,report);
    esp_err_t ret = esp_bt_hid_device_send_report(ESP_HIDD_REPORT_TYPE_INTRDATA, 
    s_local_param._report_id, 
    s_local_param._report_size,
    s_local_param.buffer);
    if (ret) {
        ESP_LOGE("HID", "Send HID report failed: %s", esp_err_to_name(ret));
    }
    xSemaphoreGive(s_local_param.mouse_mutex);
}
/****
@param identifier 手指编号
@param touch 1-按下，或者移动 0-释放

*****/
void send_touch_msg(uint8_t identifier, uint8_t isTouch,uint8_t isInRange, int16_t x, int16_t y) {
  // calculate current contact count
  uint8_t contact = 0;
      uint8_t report_size = 7;
    // uint8_t report[report_size];

    uint8_t report_id=REPORTID_TOUCH;
      s_local_param._report_id=report_id;
    s_local_param._report_size=report_size;    
  for (int i = 0; i < CONTACT_COUNT_MAXIMUM; i++) {
    if (fingers[i].contact) {
      contact += 1;
    }
  }
    /***
        // 报告 ID
    report_data[0] = report_id;
    // 当前触摸点数
    report_data[1] = contact_count;
    // 手指标识
    report_data[2] = contact_id;
    // 触摸状态（Tip Switch 和 In Range）
    report_data[3] = (tip_switch & 0x01) | ((in_range & 0x01) << 1);
    // X 坐标（低字节）
    report_data[4] = (uint8_t)(x & 0xFF);
    // X 坐标（高字节）
    report_data[5] = (uint8_t)(x >> 8);
    // Y 坐标（低字节）
    report_data[6] = (uint8_t)(y & 0xFF);
    // Y 坐标（高字节）
    report_data[7] = (uint8_t)(y >> 8);
    ***/
      // with this declaration a data packet must be sent as:
  // byte 1   -> "contact count"        (always == 1)
  // byte 2   -> "contact identifier"   (any value)
  // byte 3   -> "Tip Switch" state     (bit 0 = Tip Switch up/down, bit 1 = In Range)
  // byte 4,5 -> absolute X coordinate  (0...10000)
  // byte 6,7 -> absolute Y coordinate  (0...10000)

  /***
     uint8_t data[] = {
      1,           
      identifier,        // contact identifier
      state,             // finger touches display
      MSB(x), LSB(x),    // x
      MSB(y), LSB(y)     // y
    };
    this->inputMultiTouch->setValue(data, 7);
    this->inputMultiTouch->notify();
  ***/
  // create data array
  uint8_t data[] = {
    1,
    identifier,        // contact identifier
    (isTouch & 0x01) |( (isInRange & 0x01) << 1),             // finger touches display
    // (uint8_t)(x & 0xFF), (uint8_t)(x >> 8),    // x
    // (uint8_t)(y & 0xFF), (uint8_t)(y >> 8)     // y
          MSB(x), LSB(x),    // x
      MSB(y), LSB(y)     // y
        
  };

    s_local_param.buffer[0] = data[0]; 
    s_local_param.buffer[1] = data[1]; 
    s_local_param.buffer[2] = data[2]; 
    s_local_param.buffer[3] = data[3]; 
    s_local_param.buffer[4] = data[4]; 
    s_local_param.buffer[5] = data[5]; 
    s_local_param.buffer[6] = data[6]; 
    // s_local_param.buffer[7] = data[7]; 

    // esp_err_t ret = esp_bt_hid_device_send_report(ESP_BT_HID_REPORT_TYPE_INPUT, report_id, report_size,report);
    
    esp_err_t ret = esp_bt_hid_device_send_report(
        ESP_HIDD_REPORT_TYPE_INTRDATA, 
        // ESP_HIDD_REPORT_TYPE_INPUT ,
    s_local_param._report_id, 
    s_local_param._report_size,
    s_local_param.buffer);
    if (ret) {
        ESP_LOGE("HID", "Send HID report failed: %s", esp_err_to_name(ret));
    }
}

void resetFingerToStart(uint8_t identifier) {
  // change finger record
  xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
  fingers[identifier].contact = 1;
  int x=0;
  int y=0;
  fingers[identifier].x = x;
  fingers[identifier].y = y;
  // send update
  send_touch_msg(identifier, 1, 1,x, y);
  fingers[identifier].contact = 0;  
  fingers[identifier].x = 0;
  fingers[identifier].y = 0;
   send_touch_msg(identifier, 0,1, x, y);
  xSemaphoreGive(s_local_param.mouse_mutex);
}

void moveFingerTo(uint8_t identifier, int16_t x, int16_t y) {
  // change finger record
  xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
  fingers[identifier].contact = 1;
  fingers[identifier].x = x;
  fingers[identifier].y = y;

  // send update
  send_touch_msg(identifier, 1,1, x, y);
  xSemaphoreGive(s_local_param.mouse_mutex);
}

void releaseFinger(uint8_t identifier) {
  xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
  // change finger record
  fingers[identifier].contact = 0;
  fingers[identifier].x = 0;
  fingers[identifier].y = 0;

  // send update
  send_touch_msg(identifier, 0,1, 0, 0);
  xSemaphoreGive(s_local_param.mouse_mutex);
}


// move the mouse left and right
void mouse_move_task(void *pvParameters)
{
    const char *TAG = "mouse_move_task";
    if(true){
        return;
    }

    ESP_LOGI(TAG, "starting");
    for (;;) {
        s_local_param.x_dir = 1;
        int8_t step = 32;

        

        resetFingerToStart(0);
        for (int i = 0; i < 2; i++) {
            xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
            s_local_param.x_dir *= -1;
            xSemaphoreGive(s_local_param.mouse_mutex);
            for (int j = 0; j < 100; j++) {
                int dx=j * step;                
                ESP_LOGI(TAG,"mv to (%d,%d), is pressed:%d",dx,0,1);
                moveFingerTo(0,dx,0);
                vTaskDelay(50 / portTICK_PERIOD_MS);
            }
        }        
        releaseFinger(0);        
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
    const char *TAG = "esp_bt_gap_cb";
    switch (event) {
    case ESP_BT_GAP_AUTH_CMPL_EVT: {
        if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
            ESP_LOGI(TAG, "authentication success: %s", param->auth_cmpl.device_name);
            esp_log_buffer_hex(TAG, param->auth_cmpl.bda, ESP_BD_ADDR_LEN);
        } else {
            ESP_LOGE(TAG, "authentication failed, status:%d", param->auth_cmpl.stat);
        }
        break;
    }
    case ESP_BT_GAP_PIN_REQ_EVT: {
        ESP_LOGI(TAG, "ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit);
        if (param->pin_req.min_16_digit) {
            ESP_LOGI(TAG, "Input pin code: 0000 0000 0000 0000");
            esp_bt_pin_code_t pin_code = {0};
            esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code);
        } else {
            ESP_LOGI(TAG, "Input pin code: 1234");
            esp_bt_pin_code_t pin_code;
            pin_code[0] = '1';
            pin_code[1] = '2';
            pin_code[2] = '3';
            pin_code[3] = '4';
            esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code);
        }
        break;
    }

#if (CONFIG_EXAMPLE_SSP_ENABLED == true)
    case ESP_BT_GAP_CFM_REQ_EVT:
        ESP_LOGI(TAG, "ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %"PRIu32, param->cfm_req.num_val);
        esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
        break;
    case ESP_BT_GAP_KEY_NOTIF_EVT:
        ESP_LOGI(TAG, "ESP_BT_GAP_KEY_NOTIF_EVT passkey:%"PRIu32, param->key_notif.passkey);
        break;
    case ESP_BT_GAP_KEY_REQ_EVT:
        ESP_LOGI(TAG, "ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!");
        break;
#endif
    case ESP_BT_GAP_MODE_CHG_EVT:
        ESP_LOGI(TAG, "ESP_BT_GAP_MODE_CHG_EVT mode:%d", param->mode_chg.mode);
        break;
    default:
        ESP_LOGI(TAG, "event: %d", event);
        break;
    }
    return;
}

void bt_app_task_start_up(void)
{

    memset(s_local_param.buffer, 0, MAX_REPORT_BUFFER_SIZE);
    for (int i = 0; i < CONTACT_COUNT_MAXIMUM; i++) {
    fingers[i].contact = 0;
    fingers[i].x = 0;
    fingers[i].y = 0;
  }
    if(true){
        ESP_LOGI(TAG,"now dont run task!!!");
        return;
    }
    s_local_param.mouse_mutex = xSemaphoreCreateMutex();

    xTaskCreate(mouse_move_task, "mouse_move_task", 2 * 1024, NULL, configMAX_PRIORITIES - 3, &s_local_param.mouse_task_hdl);
    return;
}

void bt_app_task_shut_down(void)
{
    if (s_local_param.mouse_task_hdl) {
        vTaskDelete(s_local_param.mouse_task_hdl);
        s_local_param.mouse_task_hdl = NULL;
    }

    if (s_local_param.mouse_mutex) {
        vSemaphoreDelete(s_local_param.mouse_mutex);
        s_local_param.mouse_mutex = NULL;
    }
    return;
}

void esp_bt_hidd_cb(esp_hidd_cb_event_t event, esp_hidd_cb_param_t *param)
{
    static const char * SUB_TAG = "esp_bt_hidd_cb";
    switch (event) {
    case ESP_HIDD_INIT_EVT:
        if (param->init.status == ESP_HIDD_SUCCESS) {
            appConfig.km=true;
            ESP_LOGI(SUB_TAG, "setting hid parameters");
            esp_bt_hid_device_register_app(&s_local_param.app_param, &s_local_param.both_qos, &s_local_param.both_qos);
        } else {
            appConfig.km=false;
            ESP_LOGE(SUB_TAG, "init hidd failed!");
        }
        break;
    case ESP_HIDD_DEINIT_EVT:
        appConfig.km=true;
        break;
    case ESP_HIDD_REGISTER_APP_EVT:
        appConfig.km=true;
        if (param->register_app.status == ESP_HIDD_SUCCESS) {
            ESP_LOGI(SUB_TAG, "setting hid parameters success!");
            ESP_LOGI(SUB_TAG, "setting to connectable, discoverable");
            esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
            if (param->register_app.in_use) {
                ESP_LOGI(SUB_TAG, "start virtual cable plug!");
                esp_bt_hid_device_connect(param->register_app.bd_addr);
            }
        } else {
            ESP_LOGE(SUB_TAG, "setting hid parameters failed!");
        }
        break;
    case ESP_HIDD_UNREGISTER_APP_EVT:
        if (param->unregister_app.status == ESP_HIDD_SUCCESS) {
            ESP_LOGI(SUB_TAG, "unregister app success!");
        } else {
            ESP_LOGE(SUB_TAG, "unregister app failed!");
        }
        break;
    case ESP_HIDD_OPEN_EVT:
        if (param->open.status == ESP_HIDD_SUCCESS) {
            appConfig.km=true;
            if (param->open.conn_status == ESP_HIDD_CONN_STATE_CONNECTING) {
                ESP_LOGI(SUB_TAG, "connecting...");
            } else if (param->open.conn_status == ESP_HIDD_CONN_STATE_CONNECTED) {
                ESP_LOGI(SUB_TAG, "connected to %02x:%02x:%02x:%02x:%02x:%02x", param->open.bd_addr[0],
                         param->open.bd_addr[1], param->open.bd_addr[2], param->open.bd_addr[3], param->open.bd_addr[4],
                         param->open.bd_addr[5]);
                bt_app_task_start_up();
                ESP_LOGI(SUB_TAG, "making self non-discoverable and non-connectable.");
                esp_bt_gap_set_scan_mode(ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE);
            } else {
                ESP_LOGE(SUB_TAG, "unknown connection status");
            }
        } else {
            ESP_LOGE(SUB_TAG, "open failed!");
        }
        break;
    case ESP_HIDD_CLOSE_EVT:
        ESP_LOGI(SUB_TAG, "ESP_HIDD_CLOSE_EVT");
        if (param->close.status == ESP_HIDD_SUCCESS) {
            appConfig.km=false;
            if (param->close.conn_status == ESP_HIDD_CONN_STATE_DISCONNECTING) {
                ESP_LOGI(SUB_TAG, "disconnecting...");
            } else if (param->close.conn_status == ESP_HIDD_CONN_STATE_DISCONNECTED) {
                ESP_LOGI(SUB_TAG, "disconnected!");
                bt_app_task_shut_down();
                ESP_LOGI(SUB_TAG, "making self discoverable and connectable again.");
                esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
            } else {
                ESP_LOGE(SUB_TAG, "unknown connection status");
            }
        } else {
            ESP_LOGE(SUB_TAG, "close failed!");
        }
        break;
    case ESP_HIDD_SEND_REPORT_EVT:
        if (param->send_report.status == ESP_HIDD_SUCCESS) {
            // ESP_LOGI(SUB_TAG, "ESP_HIDD_SEND_REPORT_EVT id:0x%02x, type:%d", param->send_report.report_id,
            //          param->send_report.report_type);
        } else {
            ESP_LOGE(SUB_TAG, "ESP_HIDD_SEND_REPORT_EVT id:0x%02x, type:%d, status:%d, reason:%d",
                     param->send_report.report_id, param->send_report.report_type, param->send_report.status,
                     param->send_report.reason);
        }
        break;
    case ESP_HIDD_REPORT_ERR_EVT:
        ESP_LOGI(SUB_TAG, "ESP_HIDD_REPORT_ERR_EVT");
        break;
    case ESP_HIDD_GET_REPORT_EVT:
        ESP_LOGI(SUB_TAG, "ESP_HIDD_GET_REPORT_EVT id:0x%02x, type:%d, size:%d", param->get_report.report_id,
                 param->get_report.report_type, param->get_report.buffer_size);
        if (check_report_id_type(param->get_report.report_id, param->get_report.report_type)) {
            uint8_t report_id;
            uint16_t report_len;
            if (s_local_param.protocol_mode == ESP_HIDD_REPORT_MODE) {
                report_id = 0;
                report_len = REPORT_PROTOCOL_MOUSE_REPORT_SIZE;
            } else {
                // Boot Mode
                report_id = ESP_HIDD_BOOT_REPORT_ID_MOUSE;
                report_len = ESP_HIDD_BOOT_REPORT_SIZE_MOUSE - 1;
            }
            xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
            esp_bt_hid_device_send_report(param->get_report.report_type, 
            s_local_param._report_id, 
            s_local_param._report_size,
             s_local_param.buffer);
            xSemaphoreGive(s_local_param.mouse_mutex);
        } else {
            ESP_LOGE(SUB_TAG, "check_report_id failed!");
        }
        break;
    case ESP_HIDD_SET_REPORT_EVT:
        ESP_LOGI(SUB_TAG, "ESP_HIDD_SET_REPORT_EVT");
        break;
    case ESP_HIDD_SET_PROTOCOL_EVT:
        ESP_LOGI(SUB_TAG, "ESP_HIDD_SET_PROTOCOL_EVT");
        if (param->set_protocol.protocol_mode == ESP_HIDD_BOOT_MODE) {
            ESP_LOGI(SUB_TAG, "  - boot protocol");
            xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
            s_local_param.x_dir = -1;
            xSemaphoreGive(s_local_param.mouse_mutex);
        } else if (param->set_protocol.protocol_mode == ESP_HIDD_REPORT_MODE) {
            ESP_LOGI(SUB_TAG, "  - report protocol");
        }
        xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
        s_local_param.protocol_mode = param->set_protocol.protocol_mode;
        xSemaphoreGive(s_local_param.mouse_mutex);
        break;
    case ESP_HIDD_INTR_DATA_EVT:
        ESP_LOGI(SUB_TAG, "ESP_HIDD_INTR_DATA_EVT");
        break;
    case ESP_HIDD_VC_UNPLUG_EVT:
        ESP_LOGI(SUB_TAG, "ESP_HIDD_VC_UNPLUG_EVT");
        if (param->vc_unplug.status == ESP_HIDD_SUCCESS) {
            if (param->close.conn_status == ESP_HIDD_CONN_STATE_DISCONNECTED) {
                ESP_LOGI(SUB_TAG, "disconnected!");
                bt_app_task_shut_down();
                ESP_LOGI(SUB_TAG, "making self discoverable and connectable again.");
                esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
            } else {
                ESP_LOGE(SUB_TAG, "unknown connection status");
            }
        } else {
            ESP_LOGE(SUB_TAG, "close failed!");
        }
        break;
    default:
        break;
    }
}

const char * km_start_ble(char * nickName,char * bleCode,char * provider, char * description,bool useMultiTouch)
{    

    if(appConfig.km){


        // return OP_CODE_HID_NOT_INIT;
        return OP_CODE_BLE_HAS_RUNNING;
    }

    if(proc_busy){
        return OP_CODE_BUSY;
    }
    _use_multiTouch=useMultiTouch;
    proc_busy=true;

    appConfig.nickName=nickName;
    appConfig.devcCode=bleCode;

    char _rel_bleCode[30] = "hid-";
    // 拼接字符串
    strcat(_rel_bleCode, bleCode);
    
    esp_err_t ret;
    char bda_str[18] = {0};
    
    ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));

    esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
    if ((ret = esp_bt_controller_init(&bt_cfg)) != ESP_OK) {
        ESP_LOGE(TAG, "initialize controller failed: %s", esp_err_to_name(ret));
        proc_busy=false;
        return OP_CODE_BLE_INIT_ERROR;
    }

    if ((ret = esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT)) != ESP_OK) {
        ESP_LOGE(TAG, "enable controller failed: %s", esp_err_to_name(ret));
        proc_busy=false;
        return OP_CODE_BLE_INIT_ERROR;
    }

    esp_bluedroid_config_t bluedroid_cfg = BT_BLUEDROID_INIT_CONFIG_DEFAULT();
#if (CONFIG_EXAMPLE_SSP_ENABLED == false)
    bluedroid_cfg.ssp_en = false;
#endif
    if ((ret = esp_bluedroid_init_with_cfg(&bluedroid_cfg)) != ESP_OK) {
        proc_busy=false;
        ESP_LOGE(TAG, "%s initialize bluedroid failed: %s", __func__, esp_err_to_name(ret));
        return OP_CODE_BLE_INIT_ERROR;
    }

    if ((ret = esp_bluedroid_enable()) != ESP_OK) {
        proc_busy=false;
        ESP_LOGE(TAG, "enable bluedroid failed: %s", esp_err_to_name(ret));
        return OP_CODE_BLE_INIT_ERROR;
    }

    if ((ret = esp_bt_gap_register_callback(esp_bt_gap_cb)) != ESP_OK) {
        proc_busy=false;
        ESP_LOGE(TAG, "gap register failed: %s", esp_err_to_name(ret));
        return OP_CODE_BLE_INIT_ERROR;
    }

    ESP_LOGI(TAG, "setting device name");
    // esp_bt_gap_set_device_name("HID Mouse Example");
    esp_bt_gap_set_device_name(_rel_bleCode);

    ESP_LOGI(TAG, "setting cod major, peripheral");
    esp_bt_cod_t cod;
    cod.major = ESP_BT_COD_MAJOR_DEV_PERIPHERAL;
    esp_bt_gap_set_cod(cod, ESP_BT_SET_COD_MAJOR_MINOR);

    vTaskDelay(2000 / portTICK_PERIOD_MS);

    // Initialize HID SDP information and L2CAP parameters.
    // to be used in the call of `esp_bt_hid_device_register_app` after profile initialization finishes
    do {
        s_local_param.app_param.name = "Mouse";
        s_local_param.app_param.description = description;
        s_local_param.app_param.provider = provider;
        s_local_param.app_param.subclass = ESP_HID_CLASS_MIC;
        if(_use_multiTouch){
        //多点触控
        // s_local_param.app_param.desc_list = hid_mt_mouse_descriptor;
        // s_local_param.app_param.desc_list_len = hid_mt_mouse_descriptor_len;

        s_local_param.app_param.desc_list = _hidReportDescriptor;
        s_local_param.app_param.desc_list_len = hid_android_descriptor_len;
        
        }else{
            //--传统鼠标
        s_local_param.app_param.desc_list = hid_mouse_descriptor;
        s_local_param.app_param.desc_list_len = hid_mouse_descriptor_len;
        }
        memset(&s_local_param.both_qos, 0, sizeof(esp_hidd_qos_param_t)); // don't set the qos parameters
    } while (0);

    // Report Protocol Mode is the default mode, according to Bluetooth HID specification
    s_local_param.protocol_mode = ESP_HIDD_REPORT_MODE;

    ESP_LOGI(TAG, "register hid device callback");
    esp_bt_hid_device_register_callback(esp_bt_hidd_cb);

    ESP_LOGI(TAG, "starting hid device");
    esp_bt_hid_device_init();

#if (CONFIG_EXAMPLE_SSP_ENABLED == true)
    /* Set default parameters for Secure Simple Pairing */
    esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE;
    esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_NONE;
    esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t));
#endif

    /*
     * Set default parameters for Legacy Pairing
     * Use variable pin, input pin code when pairing
     */
    esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
    esp_bt_pin_code_t pin_code;
    esp_bt_gap_set_pin(pin_type, 0, pin_code);
    ESP_LOGI(TAG, "Own address:[%s]", bda2str((uint8_t *)esp_bt_dev_get_address(), bda_str, sizeof(bda_str)));
    ESP_LOGI(TAG, "exiting");
    proc_busy=false;
    return OP_CODE_SUCCESS;
}



const char * hid_mobile_touch(uint8_t identifier, int16_t x, int16_t y)
{
    
    if(appConfig.km){


        return OP_CODE_HID_NOT_INIT;
        
    }
    xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
//   this->send(identifier, 1, x, y);
    send_touch_msg(identifier,1,1,x,y);
    xSemaphoreGive(s_local_param.mouse_mutex);
    return OP_CODE_SUCCESS;
}

const char * hid_mobile_release(uint8_t identifier) 
{
    
    if(appConfig.km){


        return OP_CODE_HID_NOT_INIT;
        
    }
    xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
    send_touch_msg(identifier,0,0,0,0);
//   this->send(identifier, 0, 0, 0);
    xSemaphoreGive(s_local_param.mouse_mutex);

    return OP_CODE_SUCCESS;
}

const char * hid_mobile_tap(uint8_t identifier, int16_t x, int16_t y)
{
    
    if(appConfig.km){


        return OP_CODE_HID_NOT_INIT;
        
    }
    xSemaphoreTake(s_local_param.mouse_mutex, portMAX_DELAY);
    hid_mobile_touch(identifier, x, y);
    hid_mobile_release(identifier);
    xSemaphoreGive(s_local_param.mouse_mutex);
    return OP_CODE_SUCCESS;
}